#include "commandmanager.h"
#include "utils/Config.h"
#include "utils/logger.h"
#include <QStringList>
#include "crypto/loginhelper.h"
#include "main.h"

CommandManager::CommandManager(QObject *parent) :
    QObject(parent)
{
}
void CommandManager::ParseCmd(QString line)
{
    QStringList args=line.split(' ');
    if(args.at(0).toLower()== tr("createacc") && args.count() > 2){
            CreateAcc(args.at(1),args.at(2));
    }else if(args.at(0).toLower()== tr("cls")){
        #if defined( __WIN32__ ) || defined( WIN32 ) || defined( _WIN32 )
            std::system ( "CLS" );
        #else
            std::system ( "clear" );
        #endif
    }else if(args.at(0).toLower()== tr("tstpacket") && args.count() > 2){
        SendTestCmd(args.at(1),args.at(2));
    }else if(args.at(0).toLower()== tr("tstpacketrange") && args.count() > 2){
        SendTestRangeCmd(args.at(1), args.at(2), args.at(3));
    }
}

void CommandManager::CreateAcc(QString username, QString pass)
{
    if(LoginHelper::AddUser(username,pass))
    {
      _log->LogIt(tr("Usuario %1 creado.").arg(username));
    }else{
      _log->LogIt(tr("Error al crear usuario %1").arg(username));
    }
}

void CommandManager::SendTestCmd(QString ip, QString packet)
{
    QMap<int, Player*>::iterator i;
    for (i = LPlayers.begin(); i != LPlayers.end(); ++i)
    {
        Player* pl=(Player*)i.value();
        if(pl->GetSkt()->peerAddress().toString()==ip)
        {
            _log->LogIt(tr("Sending test to %1").arg(ip));
            QByteArray buf= QByteArray::fromHex(packet.toAscii());
            pl->GetSkt()->Send(buf);
            return;
        }
    }
   _log->LogIt(tr("Ip %1 not connected").arg(ip));
}

void CommandManager::SendTestRangeCmd(QString ip, QString count, QString packet)
{
        Player* pl=0;
        QByteArray buf= QByteArray::fromHex(packet.toAscii());
        quint8 max=count.toUShort();

        QMap<int, Player*>::iterator i;
        for (i = LPlayers.begin(); i != LPlayers.end(); ++i)
        {
            if(((Player*)i.value())->GetSkt()->peerAddress().toString()==ip)
            {
                pl=(Player*)i.value();
                break;
            }
        }
        if(pl==NULL)
        {
            _log->LogIt(tr("Ip %1 not connected").arg(ip));
            return;
        }
        max+=(*buf.data());
        for(quint8 i = (*buf.data());i<max ;i+=2)
        {
            _log->LogIt(tr("Sending cmd %1").arg(i));
            pl->GetSkt()->Send(buf);
            (*buf.data())=i;
        }
}
